package cn.krui.helper;

import cn.krui.helper.db.DBHelper;
import cn.krui.helper.db.PageModel;
import cn.krui.helper.pub_sub.Publisher;
import cn.krui.helper.tools.ApplicationRunnerX;

import javax.annotation.PostConstruct;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author zc
 */
@Configuration
public class ConfigurationBean {

  @Autowired
  private SqlSessionFactory m_factory;

  @Value("${cn.rui.helper.page-model:LIMIT}")
  private PageModel m_pageModel;

  @Value("${spring.datasource.url:}")
  private String datasourceUrl;

  @Value("${spring.datasource.driver-class-name:}")
  private String datasourceDriverClassName;

  public static SqlSessionFactory factory;

  public static PageModel pageModel;

  public static boolean isOracle;

  @PostConstruct
  public void init() {
    factory = this.m_factory;
    pageModel = this.m_pageModel;
    if (this.datasourceUrl != null) {
      isOracle = this.datasourceUrl.toLowerCase().startsWith("jdbc:oracle:");
    } else if (this.datasourceDriverClassName != null) {
      isOracle = (this.datasourceDriverClassName.toLowerCase().indexOf("oracle") != -1);
    }
  }

  @Bean
  @Scope("prototype")
  public DBHelper dbHelper(SqlSessionFactory factory, @Value("${cn.rui.helper.page-model:}") PageModel pageModel) {
    return new DBHelper(factory, pageModel, true, false);
  }

  @Value("${spring.redis.host:127.0.0.1}")
  private String spring_redis_host;
  @Value("${spring.redis.port:6379}")
  private int spring_redis_port;
  @Value("${spring.redis.timeout:6000}")
  private int spring_redis_timeout;
  @Value("${spring.redis.password:}")
  private String spring_redis_password;
  @Value("${spring.redis.prefix:qr:}")
  private String spring_redis_prefix;

  @Autowired
  private StringRedisTemplate redisTemplate;

  @Bean
  @Scope("prototype")
  public Publisher publisher() {
    Publisher _pub = new Publisher(spring_redis_host, spring_redis_port, spring_redis_timeout, spring_redis_password,redisTemplate,spring_redis_prefix);
    return _pub;
  }

  
  @Autowired
  private Publisher publisher;

  @Bean
  @Scope
  public ApplicationRunnerX applicationRunnerX() {
    return new ApplicationRunnerX(redisTemplate,publisher,spring_redis_prefix);
  }


}
